package com.jin.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jin.common.utils.HttpUtils;
import com.jin.gulimall.member.entity.MemberLevelEntity;
import com.jin.gulimall.member.exception.PhoneExistsException;
import com.jin.gulimall.member.exception.UsernameExistsException;
import com.jin.gulimall.member.vo.MemberLoginVo;
import com.jin.gulimall.member.vo.MemberRegistVo;
import com.jin.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jin.common.utils.PageUtils;
import com.jin.common.utils.Query;

import com.jin.gulimall.member.dao.MemberDao;
import com.jin.gulimall.member.entity.MemberEntity;
import com.jin.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity=memberDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //在设置用户名和手机号之前，需要判断用户名和手机号是否唯一
        //此处采用异常机制，为了让controller感知到异常
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());
        //密码可是需要加密的
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(vo.getPassword());
        memberEntity.setPassword(password);
        //其他要设置的默认属性
        //将信息插入到数据库中
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistsException{
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile>0){
            //要抛出异常
            throw new PhoneExistsException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistsException{
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            //要抛出异常
            throw new UsernameExistsException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAccout = vo.getLoginAccout();
        //需要根据账号查询Member实体类，从而获取密码进行匹配
        MemberDao memberDao = this.baseMapper;
        MemberEntity member = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAccout).or().eq("mobile", loginAccout));
        if(member!=null){
            String passwordDB = member.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String password = vo.getPassword();
            boolean matches = encoder.matches(password, passwordDB);
            if(matches){
                //成功
                return member;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //登录和注册的合并逻辑
        String uid = socialUser.getUid();
        //登录
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity!=null){
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            memberDao.updateById(update);
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        }
        //没有查到该用户，需要注册新这个用户
        MemberEntity regist = new MemberEntity();
        try {
            //进行查询信息
            Map<String, String> map = new HashMap<>();
            map.put("access_token", socialUser.getAccess_token());
            map.put("uid", socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);
            if(response.getStatusLine().getStatusCode()==200){
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                regist.setNickname(name);
                regist.setGender("m".equals(gender)?1:0);
            }
        }catch (Exception e){}
        regist.setSocialUid(socialUser.getUid());
        regist.setAccessToken(socialUser.getAccess_token());
        regist.setExpiresIn(socialUser.getExpires_in());
        memberDao.insert(regist);
        return regist;
        //applications over the unaudited use restrictions!
    }
}